package cn.heroes.weixin.commons;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Xml工具类
 * 
 * @author cq
 * 
 */
public class XmlUtils {

	private static final Logger logger = LoggerFactory
			.getLogger(XmlUtils.class);

	/**
	 * xml to bean
	 * 
	 * @param xml
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T toBean(String xml, Class<T> clazz) {
		try {
			JAXBContext jc = JAXBContext.newInstance(clazz);
			Unmarshaller u = jc.createUnmarshaller();
			return (T) u.unmarshal(new StringReader(xml));
		} catch (Exception e) {
			logger.error("", e);
			return null;
		}
	}

	/**
	 * bean to xml
	 * 
	 * @param bean
	 * @return
	 */
	public static String fromBean(Object bean) {
		try {
			JAXBContext jc = JAXBContext.newInstance(bean.getClass());
			Marshaller m = jc.createMarshaller();

			// 是否格式化输出
			// jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
			// false);

			// 去掉生成xml的默认报文头。
			m.setProperty(Marshaller.JAXB_FRAGMENT, true);
			StringWriter sw = new StringWriter();
			m.marshal(bean, sw);
			return sw.toString();
		} catch (Exception e) {
			logger.error("", e);
			return null;
		}
	}
}
